package com.example.administrator.nurse.util;

import android.os.AsyncTask;
import android.util.Log;

import com.example.administrator.nurse.NetWork.internetHelper;
import com.example.administrator.nurse.common;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;


/**
 * Created by LinGuanHong(林冠宏) on 2015/11/17.
 * 本类的诞生：
 * 1，为了更好地处理 网络编程 中的多种情况
 * 2，减少开发代码
 * 3，面向对象
 */
public class commonAsyncTask extends AsyncTask<String,Void,String> {

    private onProgressBarOperation myOnProgressBarOperationListener;
    private onDealWithDataListener myOnDealWithDataListener;
    private postDataConfigListener myPostDataConfigListener;
    private onGetDataJsonListener  myOnGetDataJsonListener;

    public commonAsyncTask(onGetDataJsonListener myOnGetDataJsonListener){
        this.myOnGetDataJsonListener = myOnGetDataJsonListener;
    }

    public commonAsyncTask(onDealWithDataListener myOnDealWithDataListener){
        this.myOnDealWithDataListener = myOnDealWithDataListener;
    }

    public commonAsyncTask(
            onProgressBarOperation myOnProgressBarOperationListener,
            onGetDataJsonListener myOnGetDataJsonListener){
        this.myOnGetDataJsonListener = myOnGetDataJsonListener;
        this.myOnProgressBarOperationListener = myOnProgressBarOperationListener;
    }

    public commonAsyncTask(
            onProgressBarOperation myOnProgressBarOperationListener,
            onDealWithDataListener myOnDealWithDataListener){
        this.myOnDealWithDataListener = myOnDealWithDataListener;
        this.myOnProgressBarOperationListener = myOnProgressBarOperationListener;
    }

    public commonAsyncTask(
            postDataConfigListener myPostDataConfigListener,
            onDealWithDataListener myOnDealWithDataListener){
        this.myPostDataConfigListener = myPostDataConfigListener;
        this.myOnDealWithDataListener = myOnDealWithDataListener;
    }

    public commonAsyncTask(
            onProgressBarOperation myOnProgressBarOperationListener,
            postDataConfigListener myPostDataConfigListener,
            onDealWithDataListener myOnDealWithDataListener){
        this.myPostDataConfigListener = myPostDataConfigListener;
        this.myOnDealWithDataListener = myOnDealWithDataListener;
        this.myOnProgressBarOperationListener = myOnProgressBarOperationListener;
    }

    // 开始线程和结束后的 UI 操作接口
    public void setOnProgressBarOperationListener(onProgressBarOperation myOnProgressBarOperationListener){
        this.myOnProgressBarOperationListener = myOnProgressBarOperationListener;
    }

    // 配置线程信息的接口,例如 url
    /*public void setUserInfoConfigListener(userInfoConfigListener myUserInfoConfigListener){
        this.myUserInfoConfigListener = myUserInfoConfigListener;
    }*/

    // 使用post上传数据的接口
    public void setOnDealWithDataListener(onDealWithDataListener myOnDealWithDataListener){
        this.myOnDealWithDataListener = myOnDealWithDataListener;
    }

    // 使用我帮你处理好 jsonArr 和 jsonObj 的接口
    public void setPostDataConfigListener(postDataConfigListener myPostDataConfigListener){
        this.myPostDataConfigListener = myPostDataConfigListener;
    }

    // 自定义完全处理返回的 json 的接口
    public void setOnGetDataJsonListener(onGetDataJsonListener myOnGetDataJsonListener){
        this.myOnGetDataJsonListener = myOnGetDataJsonListener;
    }

    public static String getString(JSONObject jsonObject,String target,String def){
        try{
            return jsonObject.isNull(target)?def:jsonObject.getString(target);
        }catch (Exception e){
            common.Log("public static String getString exception is " + e.toString());
        }
        return "";
    }

    public static int getInt(JSONObject jsonObject,String target,int def){
        try{
            return jsonObject.isNull(target)?def:jsonObject.getInt(target);
        }catch (Exception e){
            common.Log("public static String getString exception is " + e.toString());
        }
        return 0;
    }

    public interface initJsonListener{
        void initJsonOp(int length, JSONArray jsonArrayTemp);
        void initJsonStr(String data);
    }

    public interface initJsonObjListener{
        void initJsonObj(JSONObject jsonObjTemp);
        void initJsonStr(String data);
    }

    public static void initJson(String json,String error,initJsonListener initJsonListener){
        //List<String> datas = new ArrayList<>();
        try{
            JSONArray jsonArray = new JSONArray(json);
            JSONArray jsonArrayTemp;
            JSONObject jsonObject;// = new JSONObject(json);
            JSONObject jsonObjectTemp;
            int length = jsonArray.length();int lengthTemp;
            for(int i=0;i<length;i++){
                jsonObject = jsonArray.getJSONObject(i);
                if(i==0){
                    String head = getString(jsonObject,"head","");
                    jsonArrayTemp = new JSONArray(head);
                    lengthTemp = jsonArrayTemp.length();
                    for(int j=0;j<lengthTemp;j++){
                        jsonObjectTemp = jsonArrayTemp.getJSONObject(j);
                        if(getInt(jsonObjectTemp,"ret",1)!=0){
                            common.Toast(getString(jsonObjectTemp, "msg", error));
                            //return null;
                            return;
                        }
                    }
                }else {
                    String data = commonAsyncTask.getString(jsonObject, "data", "");
                    jsonArrayTemp = new JSONArray(data);
                    lengthTemp = jsonArrayTemp.length();
                    if(initJsonListener!=null){
                        initJsonListener.initJsonOp(lengthTemp,jsonArrayTemp);
                    }
                    /*for (int j = 0; j < lengthTemp; j++) {
                        jsonObjectTemp = jsonArrayTemp.getJSONObject(j);

                    }*/
                }
            }
        }catch (JSONException e){
            common.Log("init json EX is " + e.toString());
        }
        //return datas;
    }

    public static void initJsonSecond(String json,String error,initJsonObjListener initJsonListener){
        //List<String> datas = new ArrayList<>();
        try{
            JSONObject jsonObject = new JSONObject(json);
            String head = getString(jsonObject,"head","");
            String data = getString(jsonObject,"data","");
            JSONObject jsonArrayHeadObj = new JSONObject(head);

            if(getInt(jsonArrayHeadObj,"ret",1)!=0){
                common.Toast(getString(jsonArrayHeadObj, "msg", error));
                //return null;
                return;
            }else{
                JSONObject jsonArrayDataObj = new JSONObject(data);
                if(initJsonListener!=null){
                    initJsonListener.initJsonObj(jsonArrayDataObj);
                }
            }
        }catch (JSONException e){
            common.Log("init json exception is " + e.toString());
        }
        //return datas;
    }

    public static void initJsonThree(String json,String error,initJsonListener initJsonListener){
        //List<String> datas = new ArrayList<>();
        String dataOp = "加载完毕!";
        try{
            JSONObject jsonObject = new JSONObject(json);
            String head = getString(jsonObject,"head","");
            String data = getString(jsonObject,"data","");
            JSONObject jsonArrayHeadObj = new JSONObject(head);

            if(getInt(jsonArrayHeadObj,"ret",1)!=0){
                common.Toast(getString(jsonArrayHeadObj, "msg", error));
                //return null;
                return;
            }else{
                dataOp = getString(jsonArrayHeadObj,"msg",error);
                if(!data.equals("{\"null\":\"null\"}")){
                    JSONArray jsonArrayDataObj = new JSONArray(data);
                    int lengthTemp = jsonArrayDataObj.length();
                    if (initJsonListener != null) {
                        initJsonListener.initJsonOp(lengthTemp, jsonArrayDataObj);
                    }
                }else{
                    if(initJsonListener!=null){
                        common.Log("null json "+json);
                        if(!dataOp.trim().equals("成功")){
                            initJsonListener.initJsonStr(dataOp);
                        }else{
                            initJsonListener.initJsonStr("null");
                        }
                    }
                }
            }
        }catch (JSONException e){
            //common.Toast("暂无数据!");
            if(initJsonListener!=null){
                initJsonListener.initJsonStr(dataOp);
            }
            common.Log("initJsonThree init json exception is " + e.toString());
        }
        //return datas;
    }

    // 如果你要增加网络链接的判断，请在执行该异步之前判断，或者在 showProgressBar() 里面处理
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if(myOnProgressBarOperationListener!=null){
            myOnProgressBarOperationListener.showProgressBar();
        }
    }

    @Override
    protected String doInBackground(String[] params) {

        try {
            String json ="";
            if(myPostDataConfigListener!=null){ // post
                /*json = internetHelper.postDataToServer // post 处理数据的函数
                        (
                                params[0],
                                myPostDataConfigListener.setPostDatas()

                        );*/
            }else {  // get
                json = internetHelper.getStringFromUrlOnHttpRULconnection(params[0]); // 通过 url 获取信息的函数
            }
            return json;
        }catch (Exception e){
            Log.d("zzzzz", "commonAsyncTask doInBackground exception is " + e.toString());
            return null;
        }
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if(s!=null){
            Log.d("zzzzz", "commonAsyncTask onPostExecute json is " + s);
            if(myOnGetDataJsonListener!=null){   // 你可以完全自己处理 json
                myOnGetDataJsonListener.getJson(s.trim());
            }
            if(myOnDealWithDataListener!=null){  // 或者使用我的,只需要你再写个for循环
                try{
                    JSONArray jsonArr = new JSONArray(s.trim());
                    int jsonArrLength = jsonArr.length();
                    myOnDealWithDataListener.beforeDealWithJson(jsonArr,jsonArrLength);
                    JSONObject jsonOBJ = null;
                    myOnDealWithDataListener.dealWithJson(jsonArr,jsonOBJ,jsonArrLength);
                    myOnDealWithDataListener.finishDealWithJson();
                }catch (Exception e){
                    Log.d("zzzzz", "commonAsyncTask onPostExecute exception is " + e.toString());
                }
            }
        }
        if(myOnProgressBarOperationListener!=null){
            myOnProgressBarOperationListener.dimissProgressBar();
        }
    }

    // 这个必须要有，所以抽象出来
    //public abstract String setThreadUrl(int caseId); // 设置 url
    // 接口分离
    public interface onProgressBarOperation{ // 开始线程和结束后的 UI 操作接口
        void showProgressBar();  // 显示 UI
        void dimissProgressBar();// 取消 UI
    }

    public interface postDataConfigListener{ // 如果你使用post上传数据，请使用它
        //String[] setKeys();   // 设置键
        //String[] setValues(); // 设置值
        Map<String,String> setPostDatas();
    }

    public interface onGetDataJsonListener{  // 自定义完全处理返回的 json
        void getJson(String json);
    }

    public interface onDealWithDataListener{ // 使用帮你处理好 jsonArr 和 jsonObj 的接口
        void dealWithJson(JSONArray jsonArr, JSONObject jsonoBbj, int jsonLength);
        void beforeDealWithJson(JSONArray jsonArr, int length);
        void finishDealWithJson();
    }
}
